package com.blacksea.resourceserver.web.security.filter;

import com.blacksea.resourceserver.web.security.login.UnAuthenticationEntryPoint;
import com.blacksea.resourceserver.web.security.token.TokenManager;

import lombok.SneakyThrows;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 自定义授权处理 过滤器
 *
 * @author blacksea3(jxt) 2021/2/7 16:13
 */
public class TokenAuthFilter extends BasicAuthenticationFilter {

    private static final Logger LOGGER = LoggerFactory.getLogger(TokenAuthFilter.class);

    //以下两者在构造函数被赋值
    private final String reqHeaderToken;

    private final TokenManager tokenManager;

    private final AuthenticationEntryPoint authenticationEntryPoint;

    public TokenAuthFilter(AuthenticationManager authenticationManager, TokenManager tokenManager,
        String reqHeaderToken, AuthenticationEntryPoint authenticationEntryPoint) {
        super(authenticationManager);
        this.tokenManager = tokenManager;
        this.reqHeaderToken = reqHeaderToken;
        this.authenticationEntryPoint = authenticationEntryPoint;
    }

    /**
     * 过滤器实现
     *
     * @param request .
     * @param response .
     * @param chain .
     * @throws IOException .
     * @throws ServletException .
     */
    @SneakyThrows
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
        throws IOException, ServletException {
        // 获取当前用户认证权限信息
        UsernamePasswordAuthenticationToken authResult = getAuthentication(request);

        // 如果有权限信息，放入权限上下文
        if (authResult != null) {
            SecurityContextHolder.getContext().setAuthentication(authResult);
        } else {
            // 强行返回失败, 中止过滤器链
            authenticationEntryPoint.commence(request, response, new UsernameNotFoundException("未认证"));
            return;
        }

        // 放行
        chain.doFilter(request, response);
    }

    /**
     * 获取认证信息
     * <p>
     * 其中:
     * 无token, 返回空, 最终会转成无权限异常被下行方法获取
     *
     * @param request .
     * @return .
     */
    private UsernamePasswordAuthenticationToken getAuthentication(HttpServletRequest request) {
        // 从Header获取Token
        String token = request.getHeader(reqHeaderToken);

        if (token == null || token.equals("")) {
            return null;
        } else {
            //从token获取用户名, 警告: 以下一行包含远程HTTP请求
            String username = tokenManager.getUserByTokenFromCache(token);
            if (username == null || "".equals(username)) {
                try {
                    username = tokenManager.getUserByTokenFromRemote(token);
                } catch (Exception e) {
                    throw e;
                }
                if (username == null) {
                    // token有问题, 返回空
                    return null;
                } else {
                    tokenManager.addTokenToCache(token, username);
                }
            }

            // 当前未涉及权限控制
            // List<String> permissions = new ArrayList<>();
            // Collection<GrantedAuthority> authorities = new ArrayList<>();
            // for (String permission:permissions){
            //     authorities.add(new SimpleGrantedAuthority(permission));
            // }
            return new UsernamePasswordAuthenticationToken(username, token, new ArrayList<>());
        }
    }

    /**
     * 获取cookie的值
     *
     * @param request .
     * @param name .
     * @return .
     */
    public static String getCookie(HttpServletRequest request, String name) {
        Cookie[] cookies = request.getCookies();
        if (null == cookies || cookies.length == 0) {
            return null;
        }
        for (Cookie c : cookies) {
            if (c.getName().equals(name)) {
                return c.getValue();
            }
        }
        return null;
    }
}
